const { app,screen,ipcMain,BrowserWindow,dialog } = require('electron')
const fs = require('fs')
var cmdFun = require("./spawn")
const player = require('node-wav-player');
// var config = require("~/config/index")
const config = require('../../config/index');
var stockCfg = require('../../config/stock.json');
global.stockCfg = stockCfg;
// var downloadUtil = require("./download") //通过访问进行文件下载
var downloadUtil = require("./download2")  //直接检索代码进行下载

if(!app) return;


if (!fs.existsSync(config.defPath)) {
  try{
    fs.mkdirSync(config.defDir)
  }catch(ex){
    console.info("config file write error:"+ex.message)
  }
  saveConfigFile(stockCfg,(err)=>{
    if(err){
      console.info("config file write error:"+err)
    }else{
      console.info("config file write success:"+config.defPath)
    }
  });
}else{
  console.info("config file already exists:"+config.defPath)
  fs.readFile(config.defPath,"utf8",(err,data)=>{
  	if(err){
      
    }else{
      var cfg = JSON.parse(data)
      Object.assign(stockCfg, cfg);
      global.stockCfg = stockCfg;
    }
  })
}

//获取默认的配置信息
ipcMain.on("getConfig",(event,msg)=>{
  fs.readFile(config.defPath,"utf8",(err,data)=>{
  	if(err){
      event.sender.send('setConfigRes', "{}");
    }else{
      event.sender.send('setConfigRes', JSON.parse(data));
    }
  })
});

ipcMain.on("saveConfig",(event,cfgInfo)=>{
  saveConfigFile(cfgInfo,(err)=>{
    event.sender.send('saveConfigRes', err);
    if(!err){
      if( typeof(cfgInfo)=="string"){
        cfgInfo = JSON.parse(cfgInfo);
      }
      Object.assign(stockCfg, cfgInfo);
      global.stockCfg = stockCfg;
    }
  });
});

ipcMain.on("doCmd",(event,param={})=>{
  try{
    if(!param.name || !param.cmd){
      console.error("doCmd 参数缺失")
      return;
    }
    cmdFun(param.cmd,(isSucc,info)=>{
      event.sender.send(param.name+'Res', {isSucc:isSucc,info:info,cmd:param.cmd});
    },param.param);
  }catch(ex){
    try{
      event.sender.send(param.name+'Res', {isSucc:false,info:"执行异常:"+ex.message,cmd:param.cmd});
    }catch(ex){

    }
  }
});


ipcMain.on("updateKPLList",(event,list)=>{
  global.tradeWin.webContents.send('setKplListRes', list);
});


//右下角浮窗显示异常信息
ipcMain.on("showBox",(event,msg,type)=>{
  global.showBox(msg,type)
});

global.showBox=function(msg,type){
  var path = './res/wav/alerm.wav';
  if(type=="big"){
    path = './res/wav/bigevent.wav';
  }
  player.play({ path: path}).then(() => {}).catch((error) => { console.error("alermPlayerError:"+error); });
  if(!global.tipWin){
    console.error("global.tipWin is null");
    return;
  }
  console.log("showMsg:",msg)
  global.tipWin.webContents.executeJavaScript(`window.addMsg("${msg}");`, true)
  .then((result) => {
    // console.log(result) // Will be the JSON object from the fetch call
  })
}


ipcMain.on("showDFCF",(event,msg,type)=>{
  global.dfcfWin.show()
});

function saveConfigFile(cont,cb){
  if(typeof(cont)=="string" || typeof(cont)=="String"){

  }else{
    cont = JSON.stringify(cont);
  }
  cont = formatJson(cont);
  console.info("write config file:"+cont)
  fs.writeFile(config.defPath, cont, 'utf8', (err)=>{
    cb(err)
  });
}


ipcMain.on("initDlInfo",(event,savePath,url)=>{
  downloadUtil.initDlInfo(savePath,url)
});

ipcMain.on("getDlInfo",(event,param={})=>{
  try{
      var dlinfo = downloadUtil.getDlInfo();
      event.sender.send('getDlInfoRes', {isSucc:true,info:dlinfo});
  }catch(ex){
    try{
      event.sender.send('getDlInfoRes', {isSucc:false,info:"执行异常:"+ex.message});
    }catch(ex){

    }
  }
});
ipcMain.on("dealFilesPath",(event,param={})=>{
  try{
      downloadUtil.dealFilesPath();
      event.sender.send('dealFilesPathRes', {isSucc:true});
  }catch(ex){
    try{
      event.sender.send('dealFilesPathRes', {isSucc:false,info:"执行异常:"+ex.message});
    }catch(ex){

    }
  }
});

ipcMain.on('selFile', function (event,p) {
    dialog.showOpenDialog({
      properties: [p]
    }).then(result => {
      // console.log(result.canceled)
      // console.log(result.filePaths)
      if(result.filePaths){
        event.sender.send('selFileRes', result.filePaths[0])
      }
    }).catch(err => {
      console.log(err)
    })
});
  


function formatJson(json, options){
  var reg = null,
  formatted = '',
  pad = 0,
  PADDING = '  ';
  options = options || {};
  options.newlineAfterColonIfBeforeBraceOrBracket = (options.newlineAfterColonIfBeforeBraceOrBracket === true) ? true : false;
  options.spaceAfterColon = (options.spaceAfterColon === false) ? false : true;
  if (typeof json !== 'string') {
      json = JSON.stringify(json);
  } else {
      //json = JSON.parse(json);
      //json = JSON.stringify(json);
  }
  json = json.replace('\r\n\r\n',"\r\n");
  reg = /([\{\}])/g;
  json = json.replace(reg, '\r\n$1\r\n');
  reg = /([\[\]])/g;
  json = json.replace(reg, '\r\n$1\r\n');
  reg = /(\,)/g;
  json = json.replace(reg, '$1\r\n');
  reg = /(\r\n\r\n)/g;
  json = json.replace(reg, '\r\n');
  reg = /\r\n\,/g;
  json = json.replace(reg, ',');
  if (!options.newlineAfterColonIfBeforeBraceOrBracket) {
      reg = /\:\r\n\{/g;
      json = json.replace(reg, ':{');
      reg = /\:\r\n\[/g;
      json = json.replace(reg, ':[');
  }
  if (options.spaceAfterColon) {
      reg = /\:/g;
      json = json.replace(reg, ':');
  }
  (json.split('\r\n')).forEach(function (node, index) {
          var i = 0,
              indent = 0,
              padding = '';

          if (node.match(/\{$/) || node.match(/\[$/)) {
              indent = 1;
          } else if (node.match(/\}/) || node.match(/\]/)) {
              if (pad !== 0) {
                  pad -= 1;
              }
          } else {
              indent = 0;
          }

          for (i = 0; i < pad; i++) {
              padding += PADDING;
          }

          formatted += padding + node + '\r\n';
          pad += indent;
      }
  );
  return formatted;
}